<template>
  <div class="rhyme-plan-detail saleMarketRight">
    <el-main>
      <div class="space-between" style="display: flex">
        <p style="font-weight: bold">整体节奏规划</p>
        <el-row>
          <el-button style="font-weight: bold" type="info" size="mini" label='0' @click="setStageVisible()">阶段设置</el-button>
          <el-button style="font-weight: bold" type="primary" size="mini" label="1" @click="getStages()">新增节奏</el-button>
        </el-row>
      </div>
      <div class="space-between" style="display: flex;margin: 15px 0">
        <div>
          <el-radio-group  size="small" v-model="year" @change="timeChange">
            <el-radio-button label="0">年</el-radio-button>
            <el-radio-button label="1">月</el-radio-button>
          </el-radio-group>
          <el-input-number size="small" v-model="ganttYear" @change="timeChange"></el-input-number>
          <el-input-number v-if="year=='1'" size="small" :min="1" :max="12" v-model="monthSet" @change="timeChange"></el-input-number>
        </div>
        <el-row>
          <!--<el-button type="primary" size="mini" label="1" plain>仅显示有的事件</el-button>-->
        </el-row>
      </div>
      <div class="plan-detail-container">
        <div class="plan-detail-item plan-detail-left">
          <div class="detail-item-container left-item-container boederSet">
            <!--<div class="titleHeader"><span>节奏规划(</span><span v-text="activeNameSwitch"></span><span>)</span></div>-->
            <div class="plan-detail-left-container">
              <div class="cadence-itemSet" v-for="(item,index) in cadenceItems" :key="index">
                <div class="cadence-item cadence-item-left">
                  <span class="circleNormal" :style="{background: item.color}"></span>
                </div>
                <div class="cadence-item cadence-item-center">
                  <div style="margin-bottom: 6px"><span v-text="item.startTime"></span><span>至</span><span v-text="item.endTime"></span></div>
                  <div style="word-wrap: break-word;word-break: break-all;font-weight: bold" v-text="item.activityTheme"></div>
                </div>
                <div class="cadence-item cadence-item-right" ><span class="el-icon-edit-outline" @click="editRhyme(item.activityId)"></span><span class="el-icon-delete" @click="delRhymes(item.activityId)"></span></div>
              </div>
            </div>
          </div>
        </div>
        <div class="plan-detail-item plan-detail-right">
          <div class="detail-item-container">
            <div class="stageList">
              <template v-for="(item,index) in stageDays">
              <div v-if="item.value !=0" :class="['stageItem',item.name==''?'no-border':'']" :key="index"  :style="{width: item.value*100/daySumState + '%' }">
                <div >{{item.name}}</div>
              </div>
              </template>
            </div>
            <div ref="gantt" style="width: 100%;height: 500px"></div>
          </div>
        </div>
      </div>
    </el-main>
    <el-dialog  :title="updates" class="mineSetDialog dialogHeaderFont" :visible.sync="dialogVisible" width="30%">
      <span>基本设置</span>
      <div class="contentBox">
        <el-form :inline="true" class="demo-form-inline single-form-inline locationDetail pickerOption rhyme" size="small" >
          <el-form-item label="节奏主题">
            <el-input type="text" style="width: 160px;margin-right: 10px;font-weight: bold" maxLength="20" placeholder="请输入内容" v-model="theme"></el-input>
            <el-color-picker v-model="color4" size="mini" style="position: absolute;"></el-color-picker>
            <span class="colorFont">颜色自定义</span>
          </el-form-item>
          <el-form-item label="所属阶段">
            <el-select class="selectFont" v-model="selectStage" style="width: 246px" @change="resetRange">
              <el-option class="selectFont" v-for="(item,index) in stageList" :key="index" :label="item.stageName+'('+item.sTime+'-'+item.eTime+')'" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动周期 ">
            <el-date-picker style="width: 256px;font-weight: bold" v-model="value6" @change="checkRange" type="daterange" value-format="yyyy-MM-dd"
                            range-separator="至" size="mini" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
            <p v-if="!errorFont" class="errorFont">*对不起，选择的活动周期必须在{{stageList[selectStage].sTime}}-{{stageList[selectStage].eTime}}内</p>
          </el-form-item>
        </el-form>
      </div>
      <span >KPI指标</span>
      <div class="contentBox">
        <el-form :inline="true" class="demo-form-inline single-form-inline locationDetail pickerOption rhyme" size="small" >
          <el-form-item :label="item.kpiName" v-for="(item,index) in kpiList" :key="index">
            <el-input-number style="width: 210px" :min="1" :max="2147483647" placeholder="请输入内容" v-model="item.kpiExpectValue"></el-input-number>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small"  type="primary" @click="updateRhymDetail">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="阶段设置" class="mineSetDialog" :visible.sync="dialogVisibleStage" width="40%">
      <div class="">
        <el-form :inline="true" class="demo-form-inline single-form-inline locationDetail pickerOption rhyme" size="small" >
          <dateSlider :productId="productId" :contState.sync="contState"></dateSlider>
        </el-form>
        <p class="errorFont" style="text-align: right;width: 100%">*规划节奏后将无法进行阶段设置！</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisibleStage = false">取 消</el-button>
        <el-button size="small"  type="primary" @click="saveRangeSet">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import dateSlider from '../dateSlider'
  let TimeNowSet = new Date()
  let start_ = `${TimeNowSet.getFullYear()}-01-01`,end_ = `${TimeNowSet.getFullYear()}-12-31`;//用户自定义时间
  import * as opreate from 'api/getData'

  export default {
    name: "rhyme-plan-detail",
    data(){
      return{
        cadenceItems: [],
        activeNameSwitch:'',
        year:'0',
        daySumState:365,
        monthSet:null,
        gantt:'',
        optionG:{},
        ganttYear:new Date().getFullYear(),
        rhymeSet:[],
        today:new Date().format('yyyy-MM-dd'),
        dialogVisible:false,
        theme:'',
        color4:'#3FCCE1',
        stageList:[],
        selectStage:0,
        value6:[],
        errorFont:true,
        kpiList:[],
        flagMonth:0,
        days:[0,31,59,90,120,151,181,212,243,273,304,334,365],
        dialogVisibleStage:false,
        setRange:{},
        rangeFlag:false,
        contState:{},
        updates:'新增节奏',
        editr:{},
        activityId:undefined,
        stageDays:[],
        productId:''
      }
    },
    components:{
      dateSlider
    },
    mounted(){
      this.getDataDetail(this.ganttYear)
      this.treeSet()
      this.getStages(1)
    },
    methods:{
      timeChange(){
        start_ =  `${this.ganttYear}-01-01`
        end_ = `${this.ganttYear}-12-31`
        this.flagMonth = 0
        if(this.year == '0'){
          this.monthSet = null
          this.daySumState = 365
        }else {
          this.monthSet ? '' : this.monthSet = new Date().format('MM')
          this.daySumState = new Date(this.ganttYear,this.monthSet,0).getDate()
          start_ = `${this.ganttYear}-${this.monthSet}-01`
          end_ = `${this.ganttYear}-${this.monthSet}-${this.daySumState}`
        }
        this.stageDays = []
        this.getDataDetail(this.ganttYear,this.monthSet)
        this.stageRangeSet()
      },
      resetRange(val){
        this.value6 = [this.stageList[val].startTime,this.stageList[val].endTime]
      },
      treeSet(){
        this.productId = this.$route.params.productId
        opreate.getProdRhythmPlan({ productId :this.productId}).then(res => {
          let data = res.data || []
          if(data.length >= 0){
            this.cadenceItems = data
          }
        }).catch(err => console.error(err))
      },
      saveRangeSet(){
        if('' == this.contState.startTime || '' == this.contState.endTime){
          this.$message.error('请填写完整的阶段设置信息')
        }else {
          opreate.setStage(this.contState).then(res => {
            if('200' == res.code){
              this.flagMonth = 0
              this.getDataDetail(this.ganttYear,this.monthSet)
              this.treeSet()
              this.$message.success('阶段设置成功')
            }else {
              this.$message.error('阶段设置失败')
            }
            this.dialogVisibleStage = false
          })
        }
      },
      editRhyme(activityId){
        this.updates = '修改节奏'
        this.dialogVisible = true
        opreate.getGantt({ activityId }).then(res => {
          this.editr = res.data[0]
          this.theme = this.editr.activityTheme
          this.color4 = this.editr.color
          this.value6 = [this.editr.startTime,this.editr.endTime]
          this.kpiList = this.editr.kpiList
          this.activityId = this.editr.activityId
          if(this.editr.stageName == '试销'){
            this.selectStage = 0
          }else if(this.editr.stageName == '预热'){
            this.selectStage = 1
          }else if(this.editr.stageName == '高潮'){
            this.selectStage = 2
          }else {
            this.selectStage = 3
          }
        })
      },
      updateRhymDetail(){
        if(this.theme.trim() == ''){
          this.$message.error('节奏主题不能为空');
          return
        }
        if(!this.errorFont){
          this.$message.error('请重新选择活动周期');
          return
        }else {
          let param = {
            stageId:this.stageList[this.selectStage].stageId,
            activityTheme:this.theme,
            color:this.color4,
            startTime:this.value6[0],
            endTime:this.value6[1],
            listKpiEntity:this.kpiList,
            activityId:this.activityId
          }
          opreate.addRhyme(param).then(res => {
            if('200' == res.code){
              this.getDataDetail(this.ganttYear,this.monthSet)
              this.treeSet()
            }else {
              this.$message.error('操作失败，请稍后再试')
            }
            this.dialogVisible = false
          })
        }
      },
      getStages(flag){
        this.updates = '新增节奏'
        this.theme = ''
        this.color4 = '#3FCCE1'
        this.activityId = undefined
        let { productId } = this.$route.params
        opreate.getKpi({ productId }).then(res => {
          if(res.code == '200'){
            this.stageList = res.data.stage
            this.kpiList = res.data.kpiName
            this.stageRangeSet()
            if(this.stageList.length>0 && !flag){
              this.dialogVisible=true
              this.value6 = [this.stageList[0].startTime,this.stageList[0].endTime]
            }else {
              if(!flag){
                this.$message.error('请先设置阶段，再规划节奏');
              }
            }
          }
        })
      },
      setStageVisible(){
        this.cadenceItems.length > 0 ? this.$message.error('已进行节奏规划，无法设置阶段'):  this.dialogVisibleStage = true
      },
      checkRange(val){
        let start = this.timeJudgement(this.stageList[this.selectStage].startTime,val[0])
        let end = this.timeJudgement(this.stageList[this.selectStage].endTime,val[1])
        this.errorFont = (start == '1' || end == '0') ? false :true
      },
      stageRangeSet(){
        this.stageDays = []
        if(this.stageList.length <= 0){
          return
        }
        this.stageList.map((item,index) => {
          if(this.timeJudgement(start_,item.endTime) == '1' || this.timeJudgement(end_,item.startTime) == '0'){
            //阶段在查看时间之前结束OR查看时间之后开始
            this.stageDays.push({name:item.stageName,value:0})
          }else if(this.timeJudgement(item.startTime,start_) == '0'){
            //阶段开始在查看时间之前，插入当前时间内天数
            if(this.timeJudgement(item.endTime,end_) != '0'){
              this.stageDays.push({name:item.stageName,value:this.DateDiff(start_,end_)})
            }else {
              this.stageDays.push({name:item.stageName,value:this.DateDiff(start_,item.endTime)})
            }
          }else if(this.timeJudgement(item.endTime,end_) == '1'){
            //阶段结束在查看时间之后，插入当前时间内天数
            if(index == '0'){
              this.stageDays.push({name:'',value:this.DateDiff(start_,item.startTime)})
            }
            this.stageDays.push({name:item.stageName,value:this.DateDiff(item.startTime,end_)})
          }else {
            //阶段在查看时间范围内，插入完整天数
            if(index == '0'){
              this.stageDays.push({name:'',value:this.DateDiff(start_,item.startTime)})
            }
            this.stageDays.push({name:item.stageName,value:this.DateDiff(item.startTime,item.endTime)})
          }
        })
      },
      delRhymes(id){
        this.$confirm('确认删除该节奏？').then(_ => {
          opreate.delRhyme({activityId:id}).then(res => {
            this.getDataDetail(this.ganttYear,this.monthSet)
            this.treeSet()
          })
        }).catch(_ => {});
      },
      getAllDate(begin, end, limit = null) { //获得两个日期间所有日期-fn2
        let return_ = [];
        let unixDbStart = new Date(begin.replace(/-/,"/")).getTime();
        let unixDeEnd =  new Date(end.replace(/-/,"/")).getTime();
        if(limit){
          for(let index = 1; index <= limit;  index ++ ){
            return_.push(`${index}-01`.padStart(5, '0'))
          }
        }else {
          for (let k = unixDbStart; k <= unixDeEnd;) {
            return_.push((new Date(parseInt(k))).format('dd'));
            k = k + 24 * 60 * 60 * 1000;
          }
        }
        return return_;
      },
      DateDiff(dateStart,dateEnd){ // 计算两个日期相差天数-sDate1和sDate2是2006-12-18格式
        let dateStartSet,dateEndSet,dayDiff;
        dateStartSet = new Date(dateStart.replace(/-/,"/")) ;
        dateEndSet = new Date(dateEnd.replace(/-/,"/"));
        dayDiff = parseInt(Math.abs(dateStartSet-dateEndSet)/1000/60/60/24)  ;//把相差的毫秒数转换为天数
        return dayDiff;
      },
      getDataDetail(year,month){
        let params = {
          productId:this.$route.params.productId,
          yearNum : year,
          monthNum: month
        }
        this.flagMonth = 0
        opreate.getGantt(params).then(res => {
          if('200' == res.code){
            this.rhymeSet = res.data || []
            this.chartRender()
          }else {
            this.$message.error('系统错误，请稍后再试')
          }
        })
      },
      timeJudgement(dateStart,dateEnd){
        let oDateStart = new Date(dateStart.replace(/-/,"/")), oDateEnd = new Date(dateEnd.replace(/-/,"/"));
        if(oDateStart.getTime() > oDateEnd.getTime()){
          return 1
        } else if(oDateStart.getTime() < oDateEnd.getTime()){
          return 0
        }else {
          return 2
        }
      },
      chartRender(){
        this.gantt = this.$echarts.init(this.$refs.gantt)
        this.optionG = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
              shadowStyle: {
                color: 'rgba(150,150,150,0.1)',
                width: 'auto',
                type: 'default'
              }
            },
            showDelay: 0,
            hideDelay: 50,
            backgroundColor: 'rgba(107,107,107,0.7)',
            textStyle: {
              fontFamily: '微软雅黑',
              fontSize: 13
            },
            formatter: (params) => {
              let tempSetB = params[1] ? params[1].name : 0
              let tempSetMine = params[3] ? params[3].data : null
              if(tempSetMine){
                let tempSet = tempSetMine.cont || {}
                let kpiList = ''
                tempSet.kpiList.map(item => {
                  let kpi = item.kpiName+'：'+item.kpiCompletionDegree +'('+item.kpiActualValue+'/'+item.kpiExpectValue+')'+'<br />'
                  kpiList = kpiList + kpi
                })
                let titleSet = "主题："+ tempSet.activityTheme +'<br />'+"类型："+ tempSet.stageName +'<br />'+"时间："+ tempSet.startTime +'至'+ tempSet.endTime+'<br />'+ kpiList + '进度：' + parseFloat(tempSetB).toFixed(2) + '%'
                return titleSet
              }else {
                return ''
              }
            }
          },
          grid: {
            borderColor: '#EFEFEF',
            left:18,
            top:20,
            right:0,
            bottom:50
          },
          xAxis: [{
            type: 'value',
            nameLocation: 'start',
            position: 'top',
            boundaryGap: true,
            axisTick: {
              show: true
            },
            min:0,
            max:this.year == '0'? 365 : this.daySumState,
            splitNumber:this.year == '0'? 12 : this.daySumState,
            splitArea: {
              show: true,
              areaStyle: {
                color: [
                  '#e8f5fe',
                  '#e2f7fb'
                ]
              }
            },
            splitLine: {
              lineStyle: {
                color: ['#EEEEEE'],
                width: 1,
                type: 'solid'
              }
            },
            axisLabel: {
              show: true,
              max:this.DateDiff(start_,end_),
              formatter: (value,index) => {
                let tempSet = this.getAllDate(start_, end_, this.year == '0' ? 12 : null)
                return tempSet[index] && tempSet[index]
              }
            }
          }],
          yAxis: [{
            type: 'category',
            show: false,
            axisTick: {
              show: true
            },
            splitLine: {
              show:true,
              lineStyle: {
                color: ['#eeeeee'],
                width: 1,
                type: 'solid'
              }
            },
            splitArea:{
              show:false
            },
            data: this.rhymeSet.map(item => {
              if(this.timeJudgement(this.today,item.startTime) == '1'){
                if(this.timeJudgement(this.today,item.endTime) == '1'){
                  return 100
                }else {
                  let plan = this.DateDiff(item.startTime,item.endTime)
                  let curr = this.DateDiff(item.startTime,this.today)
                  return Math.round(curr*100/plan)
                }
              }else {
                return 0
              }
            })
          }],
          series: [{
            name: '辅助留白',
            type: 'bar',
            barWidth: 16,
            stack: '完成度设置',
            itemStyle: {
              normal: {
                barBorderColor: 'rgba(0,0,0,0)',
                color: 'rgba(0,0,0,0)'
              },
              emphasis: {
                barBorderColor: 'rgba(0,0,0,0)',
                color: 'rgba(0,0,0,0)'
              }
            },
            data:this.rhymeSet.map(item => {
              return {
                value:this.DateDiff(start_,item.startTime),
                name:item.activityTheme
              }
            })
          }, {
            name: '完成度',
            type: 'bar',
            stack: '完成度设置',
            itemStyle: {
              normal: {
                barBorderRadius: 10,
                color: '#bcc2c8',
                label: {
                  show: false
                }
              },
              emphasis: {
                barBorderRadius: 5
              }
            },
            barGap:'-100%',
            data:this.rhymeSet.map(item => {
              if(this.timeJudgement(end_,item.endTime) == '0'){  //比较计划是否超出当前查看时间
                return this.DateDiff(item.startTime,end_)
              }else {
                return this.DateDiff(item.startTime,item.endTime)
              }
            })
          },{
            name: '辅助留白',
            type: 'bar',
            barWidth: 16,
            stack: '计划设置',
            itemStyle: {
              normal: {
                barBorderColor: 'rgba(0,0,0,0)',
                color: 'rgba(0,0,0,0)'
              },
              emphasis: {
                barBorderColor: 'rgba(0,0,0,0)',
                color: 'rgba(0,0,0,0)'
              }
            },
            data:this.rhymeSet.map(item => {
              return {
                value:this.DateDiff(start_,item.startTime),
                name:item.activityTheme
              }
            })
          }, {
            name: '计划名称',
            type: 'bar',
            stack: '计划设置',
            itemStyle: {
              normal: {
                barBorderRadius: 10,
                color: '#d9c442',
                label: {
                  show: false
                }
              },
              emphasis: {
                barBorderRadius: 5
              }
            },
            barGap:'-100%',
            data:this.rhymeSet.map(item => {
              if(this.timeJudgement(this.today,item.startTime) == '1'){
                if(this.timeJudgement(this.today,item.endTime) == '1'){   //比较计划是否超出当前查看时间
                  let newDiff = this.timeJudgement(end_,item.endTime) == '0'
                    ? this.DateDiff(item.startTime,end_)*0.7
                    : this.DateDiff(item.startTime,item.endTime)*0.7
                  return { value:newDiff, itemStyle:{ color:item.color }, cont:item }
                }else {
                  let newDiff = this.timeJudgement(end_,this.today) == '0'
                    ? this.DateDiff(item.startTime,end_)*0.7
                    : this.DateDiff(item.startTime,this.today)
                  return { value:newDiff, itemStyle:{color:item.color}, cont:item }
                }
              }else {
                return { value:0, itemStyle:{ color:item.color }, cont:item }
              }
            })
          }]
        }
        this.gantt.setOption(this.optionG)
      }
    }
  }
</script>

<style scoped>
  .stageItem{
    height: 20px;
    display: inline-block;
    line-height: 20px;
    text-align: center;
    border-left: 1px solid #c3c3c3;
    font-size: 12px;
    color: #666;
  }
  .rhyme-plan-detail{
    border: 1px solid #e3e2e2;
  }
  .stageItem:last-child{
    border-right: 1px solid #c3c3c3;
  }
  .stageList{
    height: 20px;
    margin-bottom: 12px;
  }
  .no-border{
    border-left: none;
  }
  .errorFont{
    font-size: 10px;
    width: 250px;
    color: red
  }
  .blockSet{
    display: inline-block;
  }
  .colorFont{
    position: absolute;
    right: -37px;
    font-size: 12px;
  }
  .contentBox{
    background: #fff;
    margin-top: 15px;
    margin-bottom: 15px;
    padding: 10px;
    box-sizing: border-box;
  }
  .el-icon-edit-outline{
    margin-right: 10px;
    color: #409EFF;
    cursor: pointer;
  }
  .el-icon-delete{
    color: #409EFF;
    cursor: pointer;
  }
  .plan-detail-container{
    display: flex;
    width: 100%;
  }
  .plan-detail-left{
    display: flex;
    flex: 4;
    width: 30%;
  }
  .plan-detail-right{
    display: flex;
    flex: 11;
    width: 70%;
    justify-content: flex-end;
  }
  .detail-item-container{
    width: 98%;
    display: flex;
    flex-direction: column;
  }
  .left-item-container{
    box-shadow: 0 0 4px #888888;
  }
  .plan-detail-left-container{
    display: flex;
    flex-direction: column;
  }
  .cadence-itemSet{
    display: flex;
    min-height: 80px;
    /*cursor: pointer;*/
  }
  .activeSet{
    background: #d5eefe;
    color: #409EFF;
  }
  .cadence-itemSet+ .cadence-itemSet{
    border-top: 1px solid #E0E8EF;
  }
  .cadence-item{
    display: flex;
    justify-content: center;
  }
  .cadence-item-left{
    flex: 2;
    align-items: center;
  }
  .circleNormal{
    display: flex;
    width: 8px;
    height: 8px;
    border-radius: 4px;
  }
  .cadence-item-center{
    flex-direction: column;
    flex: 7;
    padding: 12px 0;
  }
  .cadence-item-right{
    flex: 3;
    align-items: center;
  }
  .newSetContainer{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 12px;
  }
</style>
